import MySql.Cart;
import MySql.Goods;
import MySql.cartManager;
import MySql.goodsManager;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AddCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
//        out.println(46846);
        String id=request.getParameter("id");
        Goods good= null;
        try {
            good = goodsManager.getRowById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        HttpSession session=request.getSession();
        List<Goods> list=(List<Goods>) session.getAttribute("cart");
        if(list==null){
            list=new ArrayList<Goods>();
        }

        list.add(good);

        String content="";
        Double total=0.0;
        for (int i=0;i<list.size();i++){
            Goods goods=new Goods();
            goods=list.get(i);
            content+=goods.toString();
            total+=goods.getPrice();
        }


        HttpSession ownersession=request.getSession();
        String name="";
        name= (String)(ownersession.getAttribute("name"));
        Cart cart=new Cart(name,content,total);


        try {
            if(cartManager.testId(name)){
                cartManager.updateCart(cart);
            }else{
                cartManager.registerCart(cart);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        session.setAttribute("cart",list);

        response.sendRedirect("../PetWeb");
    }
}
